package com.example.com.netty.message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 杜豪波
 * @description: TODO
 * @date 2020/1/3 16:08
 */
public class NettyMsgUtil {
    private static final Logger logger = LoggerFactory.getLogger(NettyMsgUtil.class);
    public static final int MAX_MSG_SEND_NUM=3;
    public static final int START_RESEND_NUM=0;

    //消息发送统一方法
    public static boolean sendMessage(int reSendNum, Object sendData, Channel channel) {
        boolean isSuccess=false;
        try {
            //根据消息发送的结果 相应的重发处理
            ChannelFuture future =channel.writeAndFlush(sendData);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture cft) throws Exception {
                    //消息发送不成功的话 在次数内重复发送
                    if(!cft.isSuccess()) {
                        if(reSendNum<MAX_MSG_SEND_NUM) {
                            //间隔一秒再次去发送失败的消息
                            Thread.sleep(1000L);
                            sendMessage(reSendNum+1,sendData,channel);
                        }else {
                            //超过次数还没发送成功的话就关闭
                            cft.channel().close();
                        }
                    }else{
                        updateStatus(isSuccess);
                    }
                }
            });
            return isSuccess;
        }catch (Exception e) {
            logger.error("消息发送失败");
            e.printStackTrace();
            channel.close();
        }
        return isSuccess;
    }
    public static void updateStatus(boolean isSuccess) {
        isSuccess=true;
    }
}
